package com.rc.saas.mini.controller.member;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rc.saas.base.MinipBaseController;
import com.rc.saas.mini.common.base.DataTResponse;
import com.rc.saas.mini.common.mq.MqConfig;
import com.rc.saas.mini.common.mq.MqProducer;
import com.rc.saas.mini.minip.vo.LoginInfoVo;
import com.rc.saas.mini.model.member.MemberInfo;
import com.rc.saas.mini.model.member.MemberRefundApply;
import com.rc.saas.mini.model.member.MemberRefundApplyExample;
import com.rc.saas.mini.model.order.OrderInfo;
import com.rc.saas.mini.model.rc.RcMsgNotification;
import com.rc.saas.mini.model.rc.RcOperatorAccountRecord;
import com.rc.saas.mini.service.market.MarketActivityService;
import com.rc.saas.mini.service.member.MemberInfoService;
import com.rc.saas.mini.service.member.MemberRefundApplyService;
import com.rc.saas.mini.service.member.MemberRefundOrderService;
import com.rc.saas.mini.service.order.OrderInfoService;
import com.rc.saas.mini.service.rc.RcMsgNotificationService;
import com.rc.saas.mini.service.rc.RcOperatorAccountRecordService;
import com.rc.saas.mini.vo.base.RcPageVo;
import com.rc.saas.mini.vo.member.MemberRefundApplyVo;
import com.rc.saas.mini.vo.member.MemberRefundFactVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 *
 */
@Controller
@RequestMapping("/memberRefundOrder")
@Api(tags = "17.提现申请")
public class MemberRefundOrderController extends MinipBaseController {
    private static Logger logger = LogManager.getLogger(MemberRefundOrderController.class);


    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private OrderInfoService orderInfoService;

    @Autowired
    private MqProducer mqProducer;

    @Autowired
    private MemberRefundApplyService memberRefundApplyService;

    @Autowired
    private RcMsgNotificationService rcMsgNotificationService;
    @Autowired
    private RcOperatorAccountRecordService rcOperatorAccountRecordService;


    @RequestMapping(value = "/apply", method = RequestMethod.POST)
    @ApiOperation(value = "(提现)申请转账", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataTResponse<String> apply(HttpServletRequest request, MemberRefundApplyVo memberRefundApplyVo) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }

        MemberRefundApplyExample example = new MemberRefundApplyExample();
        example.createCriteria().andMemberIdEqualTo(loginInfo.getMemberId());
        example.setOrderByClause("last_updated_time desc,created_time desc");

        //List<MemberRefundApply> oldList = memberRefundApplyService.selectByExample(example);
        //List<MemberRefundApply> oldList = memberRefundApplyService.listByMemberNow(member.getMemberId());
        //if (oldList != null && oldList.size() > 0
        //        && oldList.stream()
        //        .filter(data -> "0".equals(data.getStatus()) || "1".equals(data.getStatus())
        //                || "3".equals(data.getStatus())).findFirst().orElseGet(() -> null) != null) {
        //    return DataTResponse.FAIL("用户已申请提现，请等待处理完成!");
        //}

        MemberRefundApply memberRefundApply = new MemberRefundApply();
        BeanUtils.copyProperties(memberRefundApplyVo, memberRefundApply);
        memberRefundApply.setMemberId(loginInfo.getMemberId());


        memberRefundApply.setStatus("0");
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        if (memberRefundApply.getRefundSource() == null) {
            memberRefundApply.setRefundSource("1");
        }
        if (memberRefundApply.getRefundBy() == null) {
            memberRefundApply.setRefundSource("0");
        }
        //if (StringUtils.isEmpty(memberRefundApply.getMemberRealName())
        //        || StringUtils.isEmpty(memberRefundApply.getReason()) || StringUtils.isEmpty(memberRefundApply.getRefundAmount())
        //        || (StringUtils.isEmpty(memberRefundApply.getWxOpenid()) && StringUtils.isEmpty(memberRefundApply.getAliAcount()))) {
        //    return DataTResponse.FAIL("参数不完整");
        //}

        try {
            //统计充电中订单个数
            //int count = orderInfoService.countElecOrder(member.getMemberId(), member.getTenantCode()).intValue();

            OrderInfo orderInfoNotEnd = orderInfoService.selectByNotEnd(member.getMemberId());
            if (orderInfoNotEnd != null) {
                //充电中不允许申请退款
                DataTResponse.FAIL("充电中不能提现2");
            }

            memberRefundApply.setStatus("0");
            memberRefundApply.setRefundType("0");
            memberRefundApply.setCreatedTime(new Date());
            memberRefundApply.setPaymentTime(null);
            memberRefundApply.setMemberId(member.getMemberId());
            memberRefundApply.setTenantCode(member.getTenantCode());
            memberRefundApply.setRemark(null);
            memberRefundApply.setMemberRealName(member.getNameReal());
            memberRefundApply.setWxOriginalid(member.getWechatOriginalid());
            if ("1".equals(memberRefundApply.getRefundSource())) {
                memberRefundApply.setWxOpenid(member.getWechatOpenid());
            } else {
                memberRefundApply.setWxOpenid(member.getMinipOpenid());
            }
            memberRefundApply.setWxName(member.getNameWx());
            memberRefundApply.setAliAcount(member.getAliUserId());
            if (memberRefundApply.getMemberMobile() == null) {
                memberRefundApply.setMemberMobile(member.getMobile());
            }

            if("1".equals(memberRefundApplyVo.getRefundBy())){
                memberRefundApply.setAliAcount(memberRefundApply.getMemberMobile());
                if(memberRefundApply.getAliAcount()==null||member.getNameReal()==null){
                    return DataTResponse.FAIL("申请提现失败！未绑定支付宝/未实名！");
                }
                memberRefundApply.setRealName(member.getNameReal());
                memberRefundApply.setMemberRealName(member.getNameReal());

            }
            RcOperatorAccountRecord rcOperatorAccountRecord = new RcOperatorAccountRecord();
            rcOperatorAccountRecord.setRecordType("1");
            rcOperatorAccountRecord.setExplains("提成收益提现");
            rcOperatorAccountRecord.setAmount(memberRefundApplyVo.getRefundAmount());
            rcOperatorAccountRecord.setRecordSource("0");
            rcOperatorAccountRecord.setEntryId(member.getMemberId());
            rcOperatorAccountRecord.setEntryName(member.getNickname());
            rcOperatorAccountRecord.setEntryType("1");
            rcOperatorAccountRecord.setEntryAccount(memberRefundApplyVo.getRefundAmount());
            rcOperatorAccountRecord.setOutId(1L);
            rcOperatorAccountRecord.setOutName("平台");
            rcOperatorAccountRecord.setOutType("0");
            rcOperatorAccountRecord.setStatus("1");
            rcOperatorAccountRecord.setCreatedTime(new Date());
            rcOperatorAccountRecord.setLastUpdatedTime(new Date());
            rcOperatorAccountRecord.setRemark("提现");
            rcOperatorAccountRecordService.insertSelective(rcOperatorAccountRecord);
            return memberRefundApplyService.selectFactAmount(memberRefundApply);


        } catch (Exception e) {
            logger.error("申请提现失败", e);
            return DataTResponse.FAIL("申请提现失败！");
        }
    }


    @RequestMapping(value = "/applyByGetFact", method = RequestMethod.POST)
    @ApiOperation(value = "提现数据(获取实际扣费，实际手续费)", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public DataTResponse<MemberRefundFactVo> applyByGetFact(HttpServletRequest request, MemberRefundApplyVo memberRefundApplyVo) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        MemberInfo member = memberInfoService.selectByPrimaryKey(loginInfo.getMemberId());
        if (member == null) {
            return DataTResponse.FAIL_LOGIN();
        }

        MemberRefundApply memberRefundApply = new MemberRefundApply();
        BeanUtils.copyProperties(memberRefundApplyVo, memberRefundApply);
        memberRefundApply.setMemberId(loginInfo.getMemberId());


        memberRefundApply.setStatus("0");
        if (loginInfo == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        if (memberRefundApply.getRefundSource() == null) {
            memberRefundApply.setRefundSource("1");
        }
        if (memberRefundApply.getRefundBy() == null) {
            memberRefundApply.setRefundSource("0");
        }


        memberRefundApply.setStatus("0");
        memberRefundApply.setRefundType("0");
        memberRefundApply.setCreatedTime(new Date());
        memberRefundApply.setPaymentTime(null);
        memberRefundApply.setMemberId(member.getMemberId());
        memberRefundApply.setTenantCode(member.getTenantCode());
        memberRefundApply.setRemark(null);
        memberRefundApply.setWxOriginalid(member.getWechatOriginalid());
        if ("1".equals(memberRefundApply.getRefundSource())) {
            memberRefundApply.setWxOpenid(member.getWechatOpenid());
        } else {
            memberRefundApply.setWxOpenid(member.getMinipOpenid());
        }
        memberRefundApply.setWxName(member.getNameWx());
        memberRefundApply.setAliAcount(member.getAliUserId());
        if (memberRefundApply.getMemberMobile() == null) {
            memberRefundApply.setMemberMobile(member.getMobile());
        }
        return memberRefundApplyService.sumFactAmount(memberRefundApply);

    }


    /**
     * 查询
     */
    @ApiOperation(value = "查询单个 申请记录", httpMethod = "POST")
    @RequestMapping(value = "/selectByRefundApplyId", method = RequestMethod.POST)
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "enterpriseId", paramType = "query", value = "id", required = true),
    })
    private DataTResponse<MemberRefundApply> selectByRefundApplyId(HttpServletRequest request, Long refundApplyId) {
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null || loginInfo.getMemberId() == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        if (refundApplyId == null || loginInfo.getMemberId() == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        MemberRefundApply memberRefundApply = new MemberRefundApply();

        memberRefundApply.setMemberId(loginInfo.getMemberId());
        memberRefundApply.setRefundApplyId(refundApplyId);
        List<MemberRefundApply> list = memberRefundApplyService.listByCondition(memberRefundApply);

        return DataTResponse.SUCCESS_DATA(list.stream().findFirst().orElseGet(() -> null));
    }


    /**
     * 查询列表分页
     */
    @ApiOperation("查询列表分页 提现申请记录")
    @RequestMapping(value = "/listPageByMemberRefundApply", method = RequestMethod.POST)
    @ResponseBody
    private DataTResponse<PageInfo<MemberRefundApply>> listPageByMemberRefundApply(HttpServletRequest request, MemberRefundApply memberRefundApply, RcPageVo lkPageVo) {
        //Page
        LoginInfoVo loginInfo = readLoginInfo(request);
        if (loginInfo == null || loginInfo.getMemberId() == null) {
            return DataTResponse.FAIL_LOGIN();
        }
        memberRefundApply.setMemberId(loginInfo.getMemberId());
        PageHelper.startPage(lkPageVo.getPageNo(), lkPageVo.getPageSize());
        List<MemberRefundApply> list = memberRefundApplyService.listByCondition(memberRefundApply);
        PageInfo<MemberRefundApply> pageInfo = new PageInfo<>(list);
        return DataTResponse.SUCCESS_DATA(pageInfo);
    }


}
